package com.stoney.utils;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Stony on 2015/12/16.
 */
public class ParserUrl {
    public String uri;
    public URL url;
    public String path;
    public String host;
    public String query;
    public ParserUrl(String uri) {
        this.uri = uri;
        try {
            this.url = new URL(uri);
            parser(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    final static String SEPARATOR = "/";

    public ParserUrl(URL url) {
        this.url = url;
        parser(url);
    }

    private void parser(URL url) {
        this.path = url.getPath();
        this.host = url.getHost();
        this.query = url.getQuery();
    }
    public String getOutFilePath(String dir) {
        return dir + SEPARATOR + this.host + SEPARATOR + this.path;
    }
    public String getOutFilePath(String dir, String suffix) {
        String filePath = getOutFilePath(dir);
        if(filePath.endsWith(suffix)){
            return filePath;
        }else{
            filePath += extractFileName();
            if(!filePath.endsWith(suffix)){
                filePath += extractFileQuery();
                filePath += suffix;
            }
        }
        return filePath;
    }

    public String extractFileQuery() {
        if(this.query == null){
            this.query =  "";
        }
        return this.query;
    }
    public String extractFileName() {
        String name = this.path.substring(this.path.lastIndexOf(SEPARATOR) + 1);
        if(name.equals("/") || name.length() == 0){
            return "index";
        }
        return name;
    }
    public String convertSeparator(String path){
        return path.replaceAll("/",SEPARATOR);
    }

}
